const fs = require('fs');
const env = process.argv[2] || 'prod';

const directoryMap = {
  en: 'en_US',
  ja: 'ja_JP',
  zh_tw: 'zh_TW'
};

const translateRequest = language => new Promise((resolve, reject) => {
  let directoryName = directoryMap[language];
  let jsContent = `import common from 'static/i18n/${directoryName}/common.json'
${language === 'zh_tw' ? '' : `import menu from 'static/i18n/${directoryName}/menu.json'
`}
function createXmlHttp() {
  var xmlHttp;
  try {
    xmlHttp = new XMLHttpRequest();
  } catch (e) {
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        console.log('浏览器太老，不能使用ajax');
      }
    }
  }
  return xmlHttp;
}

function ajax(isAsync) {
  var v = {};
  var xmlHttp = createXmlHttp();
  xmlHttp.open("GET", "/multilanguage/web_${env}_${language}.json", isAsync);
  xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      v = xmlHttp.responseText;
    }
  };
  xmlHttp.send(null);
  return v
}

function isJSON(str) {
  if (typeof str === 'string') {
    try {
      var obj = JSON.parse(str);
      if(typeof obj == 'object' && obj){
        return obj;
      }else{
        return {};
      }
    } catch(e) {
      return {};
    }
  }
}

let index = isJSON(ajax(false));

const i18nList = [
  common,${language === 'zh_tw' ? '' : `
  menu,`}
  index
];

let result = {};

i18nList.map(i18n => {
  result = Object.assign(result, i18n)
});

export default result;
`;
  console.log(`Writing ${language} to native... `);
  fs.writeFile(`./src/share/i18n/${directoryName}.js`, jsContent, jsWriteError => {
    if (jsWriteError) {
      reject(jsWriteError);
    } else {
      if(language !== 'zh_tw') {
        console.log(`Deleting ${language} index.json...`);
        fs.unlink(`./src/static/i18n/${directoryName}/index.json`, () => {
          resolve(language);
        })
      } else {
        console.log(`The ${language} do not need to delete index.json`);
        resolve(language);
      }
    }
  })
});

const runPromiseByStep = list => {
  const [language, ...other] = list;
  translateRequest(language).then(() => {
    console.log(`👌️️ Writing ${language} success! `);
    console.log('');
    if(list.length > 1) {
      runPromiseByStep(other);
    } else {
      console.log('Finish')
    }
  }).catch(e => {
    console.error(e);
  })
};

runPromiseByStep(['zh_tw', 'en', 'ja']);
